package com.bytic.miaosha.controller;

import com.bytic.miaosha.business.MiaoshaBusiness;
import com.bytic.miaosha.domain.MiaoshaUser;
import com.bytic.miaosha.redis.GoodsKey;
import com.bytic.miaosha.result.Result;
import com.bytic.miaosha.service.GoodsService;
import com.bytic.miaosha.service.MiaoshaUserService;
import com.bytic.miaosha.service.RedisService;
import com.bytic.miaosha.vo.GoodsVO;
import com.bytic.miaosha.vo.MiaoshaStatusVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private MiaoshaUserService userService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ThymeleafViewResolver viewResolver;

    /**
     * 为了兼容部分手机直接通过请求参数把cookie传值的情况
     *
     * 每次都要做获取token并获取用户信息的操作，麻烦，代码繁琐
     *
     * 可以用 argumentresolver 将值直接转换成对象传进来
     * @param model
     * @param tokenCookie
     * @param paramCookie
     * @return
     */
    /*@RequestMapping("/tolist")
    public String tolist(Model model,
                         @CookieValue(value = KeyConstant.COOKIE_NAME_TOKEN, required = false) String tokenCookie,
                         @RequestParam(value = KeyConstant.COOKIE_NAME_TOKEN, required = false) String paramCookie) {
        if (StringUtils.isEmpty(tokenCookie) && StringUtils.isEmpty(paramCookie)) {
            return "login";
        }
        String token = StringUtils.isEmpty(paramCookie) ? tokenCookie : paramCookie;
        MiaoshaUser user = userService.getUserByToken(token);
        if (user != null) {
            model.addAttribute("user", user);
        }
        return "goods";
    }*/

    /**
     * 1000 * 10
     * QPS: 500.6
     * @param model
     * @param user
     * @return
     */
    /*@RequestMapping("/tolist")
    public String tolist(Model model, MiaoshaUser user) {
        model.addAttribute("user", user);
        List<GoodsVO> goodsList = goodsService.listGoodsVo();
        model.addAttribute("goodsList", goodsList);
        return "goods_list";
    }*/

    /**
     * 添加页面缓存
     *
     * 1000 * 10
     *
     * QPS: 936
     *
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(value = "/tolist", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String tolist(HttpServletRequest request, HttpServletResponse response, Model model, MiaoshaUser user) {
        model.addAttribute("user", user);
        // 取缓存
        String html = redisService.get(GoodsKey.goodsList, "", String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        List<GoodsVO> goodsList = goodsService.listGoodsVo();
        model.addAttribute("goodsList", goodsList);
//        return "goods_list";
        // 手动渲染
        WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(),
                model.asMap());
        html = viewResolver.getTemplateEngine().process("goods_list", context);
        if (!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.goodsList, "", html);
        }
        return html;
    }

    /**
     * 页面缓存
     * @param request
     * @param response
     * @param model
     * @param user
     * @param id
     * @return
     */
    /*@RequestMapping(value = "/todetail/{goodsId}", produces = "text/html")
    @ResponseBody
    public String todetail(HttpServletRequest request, HttpServletResponse response, Model model, MiaoshaUser user,
                           @PathVariable("goodsId") long id) {
        model.addAttribute("user", user);
        // 取缓存
        String html = redisService.get(GoodsKey.goodsDetail, "" + id, String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        GoodsVO goods = goodsService.getGoodsVoByGoodsId(id);
        model.addAttribute("goods", goods);
        MiaoshaStatusVo miaoshaStatusVo = MiaoshaBusiness.getMiaoshaStatus(goods);
        model.addAttribute("remainSeconds", miaoshaStatusVo.getRemainSeconds());
        model.addAttribute("miaoshaStatus", miaoshaStatusVo.getMiaoshaStatus());
//        return "goods_detail";
        // 手动渲染
        WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(),
                model.asMap());
        html = viewResolver.getTemplateEngine().process("goods_detail", context);
        if (!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.goodsDetail, "" + id, html);
        }
        return html;
    }*/

    /**
     * 页面静态化
     * @param request
     * @param response
     * @param user
     * @param id
     * @return
     */
    @RequestMapping(value = "/todetail/{goodsId}")
    @ResponseBody
    public Result<MiaoshaStatusVo> todetail(HttpServletRequest request, HttpServletResponse response, MiaoshaUser user,
                           @PathVariable("goodsId") long id) {
        GoodsVO goods = goodsService.getGoodsVoByGoodsId(id);
        MiaoshaStatusVo miaoshaStatusVo = MiaoshaBusiness.getMiaoshaStatus(goods);
        miaoshaStatusVo.setGoods(goods);
        miaoshaStatusVo.setUser(user);
        return Result.success(miaoshaStatusVo);
    }
}
